package it.xiuxian.homepage.fragment

import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdNative.NativeExpressAdListener
import com.bytedance.sdk.openadsdk.TTNativeExpressAd
import com.bytedance.sdk.openadsdk.TTNativeExpressAd.ExpressAdInteractionListener
import it.xiuxian.homepage.R
import it.xiuxian.homepage.bean.Detail
import it.xiuxian.homepage.bean.ZiXunBean
import it.xiuxian.homepage.databinding.HomepageZixunFragmentBinding
import it.xiuxian.homepage.presenter.ZiXunFragmentPresenter
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.base.BaseFragment
import it.xiuxian.lib.utils.*
import it.xiuxian.lib.utils.adapter.SlimAdapter
import it.xiuxian.lib.utils.adapter.SlimInjector
import it.xiuxian.lib.utils.adapter.injector.IViewInjector
import java.util.*
import kotlin.collections.ArrayList

@Route(path = ArouterAddress.ZIXUNFRAGMENT)
class ZiXunFragment:BaseFragment<ZiXunFragmentPresenter>(){
    var binding:HomepageZixunFragmentBinding?=null
  lateinit var adapter1: SlimAdapter
    @JvmField
    @Autowired
    var erweima:String?=null
    @JvmField
    @Autowired
    var flag:String?=null
    var i=1
    private var mTTAdNative: TTAdNative? = null
    private val mHandler = Handler(Looper.getMainLooper())
    override val layoutId: Int
        get() = R.layout.homepage_zixun_fragment
    override val presenter: ZiXunFragmentPresenter
        get() = ZiXunFragmentPresenter()

    override fun isEmpty(textView: TextView?): Boolean {
        return false
    }

    override fun initView(){
        ARouter.getInstance().inject(this)
        binding= getViewDataBinding<HomepageZixunFragmentBinding>()
        binding!!.rv.layoutManager = LinearLayoutManager(requireActivity())
        //step1:初始化sdk
        val ttAdManager = TTAdManagerHolder.get()
        //step2:创建TTAdNative对象,用于调用广告请求接口
        mTTAdNative = ttAdManager.createAdNative(requireActivity())
        //step3:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary(requireActivity())
        LiveDataBus.get().with(RxBusCode.ZIXUNREFRESH).observe(this, Observer {
            getRrefresh()
        })
        LiveDataBus.get().with(RxBusCode.ZIXUNLOADMORE).observe(this, Observer {
            getMore()
        })
        mHandler.postDelayed({ loadListAd() }, 500)
        adapter1 = SlimAdapter.create().register<Detail>(
            R.layout.homepage_zixun_second_item,
            object : SlimInjector<Detail> {
                override fun onInject(
                    data: Detail?,
                    injector: IViewInjector<out IViewInjector<*>>?
                ) {

                    injector!!.text(R.id.tv_newcontent, data!!.liulannum + "人次阅读")
                        .text(R.id.tv_name, data.biaoti)
                        .clicked(R.id.ll_zong, View.OnClickListener {
                            ARouter.getInstance().build(ArouterAddress.ZIXUNDETAILACTIVITY)
                                .withString(
                                    "erweima",
                                    erweima
                                ).withString("imgurl",data.imgurl).withString("biaoti",data.biaoti).withString("id", data.id).navigation()
                        })
                    ImageUtil.setImage(data.imgurl, injector.findViewById<ImageView>(R.id.image))


                }
            }).register<TTNativeExpressAd>(
            R.layout.listitem_ad_native_express,
            object : SlimInjector<TTNativeExpressAd> {
                override fun onInject(
                    data: TTNativeExpressAd?,
                    injector: IViewInjector<out IViewInjector<*>>?
                ) {
                    data!!.setExpressInteractionListener(object : ExpressAdInteractionListener {
                        override fun onAdClicked(view: View, type: Int) {

                        }

                        override fun onAdShow(view: View, type: Int) {

                        }

                        override fun onRenderFail(view: View, msg: String, code: Int) {


                        }

                        override fun onRenderSuccess(view: View, width: Float, height: Float) {

                         /*   //返回view的宽高 单位 dp
                            TToast.show(mContext, "渲染成功")*/
                           var lay= injector!!.findViewById<FrameLayout>(R.id.iv_listitem_express)
                            lay.removeAllViews()
                            lay.addView(view)
                        }
                    })
                    /* injector!!.text(R.id.tv_newcontent, data!!.liulannum + "人次阅读")
                    .text(R.id.tv_name, data.biaoti)
                    .clicked(R.id.ll_zong, View.OnClickListener {
                        ARouter.getInstance().build(ArouterAddress.ZIXUNDETAILACTIVITY)
                            .withString(
                                "erweima",
                                erweima
                            ).withString("id", data.id).navigation()
                    })
                ImageUtil.setImage(data.imgurl, injector.findViewById<ImageView>(R.id.image))*/


                }
            }).attachTo(binding!!.rv)
    }
    private val LIST_ITEM_COUNT = 3
    private var list:ArrayList<Any> = ArrayList()
    private fun loadListAd(){
        //step4:创建feed广告请求类型参数AdSlot,具体参数含义参考文档
        val adSlot = AdSlot.Builder()
            .setCodeId("947435727")
            .setExpressViewAcceptedSize(350f, 150f) //期望模板广告view的size,单位dp
            .setAdCount(3) //请求广告数量为1到3条
            .build()
        //step5:请求广告，调用feed广告异步请求接口，加载到广告后，拿到广告素材自定义渲染
        mTTAdNative!!.loadNativeExpressAd(adSlot, object : NativeExpressAdListener {
            override fun onError(code: Int, message: String) {
                /*if ( != null) {
                    mListView.setLoadingFinish()
                }*/
                //TToast.show(this@NativeExpressListActivity, message)
            }

            override fun onNativeExpressAdLoad(ads: List<TTNativeExpressAd>) {
                /*if (mListView != null) {
                    mListView.setLoadingFinish()
                }*/
                if (ads == null || ads.isEmpty()) {
                    TToast.show(requireActivity(), "on FeedAdLoaded: ad is null!")
                    return
                }
                for (i in ads) {
                    newList.add(i)
                    adapter1.updateData(newList)
                    i.render()
                }
                // newList.addAll(ads)

                /*  for (i in 0 until LIST_ITEM_COUNT) {
                    mData.add(null)
                }*/
                // bindAdListener(ads)
            }
        })
    }

    fun getMore(){
        if(flag=="1"){
            mPresenter!!.getList((++i).toString(), "1")
        }else{
            mPresenter!!.getList((++i).toString(), "2")
        }
        loadListAd()
    }
    //@Subscribe(threadMode = ThreadMode.MAIN,code=1988)
    fun getRrefresh(){
        i=1
        if(flag=="1"){
            mPresenter!!.getList("1", "1")
        }else{
            mPresenter!!.getList("1", "2")
        }
    }
    override fun initData() {
       // super.initData()
        if(flag=="1"){
           mPresenter!!.getList("1", "1")
        }else{
            mPresenter!!.getList("1", "2")
        }
    }
var newList = ArrayList<Any>()
    fun geData(data: ZiXunBean){
        if(i==1){
            newList.clear()
            newList.addAll(data.list)
            adapter1.updateData(newList)
        }else if(i>1&&data.next!=-1){
            newList.addAll(data.list)
            adapter1.updateData(newList)
        }
        LiveDataBus.get().with(RxBusCode.ZIXUNFINISHLOAD).postValue(1)

    }

}